<template>
    <div>
        <!-- 头部：新增 + 搜索 -->
        <el-row style="margin: 10px">
            <el-col :span="12">
        <span>
        <el-button type="primary" @click="showNewInfo()">新增用户</el-button>
      </span>
            </el-col>
            <el-col :span="12">
        <span style="float: right">
          <el-input style="width: 200px" v-model="query" placeholder="输入搜索内容"/>
          <el-button type="primary" style="margin-left: 10px" @click="queryUser()">搜索</el-button>
        </span>
            </el-col>
        </el-row>

        <!-- 中间：列表 + 修改 + 删除 -->
        <el-row>
            <el-table :data="userList" border style="width: 100%;margin-left: 5px;margin-right: 5px">
                <el-table-column prop="username" label="用户名"/>
                <el-table-column prop="password" label="用户密码"/>
                <el-table-column prop="nickname" label="昵称"/>
                <el-table-column prop="picture" label="头像">
                    <template #default="scope">
                        <img :src="`data:image/png;base64,${scope.row.picture}`" alt="头像"
                             style="width: 50px; height: 50px;"/>
                    </template>
                </el-table-column>
                <el-table-column prop="enable" label="启用状态">
                    <template #default="scope">
                        <span v-if="scope.row.enable">启用</span>
                        <span v-else>禁用</span>
                    </template>
                </el-table-column>
                <el-table-column prop="user_scope_tag" :show-overflow-tooltip='true' label="授权范围"/>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="showEditInfo(scope.row)">修改</el-button>
                        <el-button link type="primary" size="small" @click="deleteInfo(scope.row.username)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 分页 -->
        <el-row :justify="'center'" style="margin-top: 10px">
            <el-pagination
                    :current-page=currentPage
                    :total=totalPage
                    @current-change="currentChange"
                    layout="prev, pager, next"
            />

        </el-row>

        <!-- 模态 -->
        <el-dialog
                v-model="showModel"
                title="用户信息"
                width="30%"
        >
            <el-form :model="userInfo" label-width="120px">
                <el-form-item label="用户名称">
                    <el-input v-model="userInfo.username"/>
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input v-model="userInfo.nickname"/>
                </el-form-item>
                <el-form-item label="用户密码">
                    <el-input v-model="userInfo.password" :disabled="passwordOn"/>
                </el-form-item>
                <el-form-item label="启用状态">
                    <el-radio-group v-model="userInfo.enable" class="ml-4">
                        <el-radio :label="true" size="large">启用</el-radio>
                        <el-radio :label="false" size="large">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="授权范围">
                    <el-checkbox-group v-model="userInfo.user_scope_tag">
                        <el-checkbox v-for="sc in scopeTag" :label="sc.tag">{{ sc.name }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="addOrUpdateInfo">提交</el-button>
        <el-button type="primary" @click="showModel = false">取消</el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import request from "/@/plugins/request.js";

const getUserList = () => {
    request.get(`/user?page=${currentPage.value}&size=${pageSize.value}`).then((res) => {
        userList.value = res.data.data;
        totalPage.value = res.data.total;
    })
}

const getScopeTag = () => {
    request.get('/admin/scope/all').then((res) => {
        scopeTag.value = res.data.data;
    })
}

const addUserRequest = () => {
    request.post('/user/add', userInfo).then((res) => {
        ElMessage(res.data.msg);
        getUserList()
    })
}

const deleteUserRequest = (username) => {
    request.delete("/user/" + username).then((res) => {
        ElMessage(res.data.msg);
        getUserList()
    })
}

const queryUserRequest = () => {
    request.get("/user/" + query.value).then((res) => {
        userList.value = res.data.data
    })
}

// 首次加载
onMounted(() => {
    getUserList()
    getScopeTag()
})

/**
 * 这是一个完整的curd + 表格 + 分页 + 搜索的模板，需要注意修改体系本身就行
 * 1.尝试写为公用部分
 * 2.优化ui布局百分比随动问题
 */

const scopeTag = ref([])

const userInfo = reactive({
    id: 1,
    username: "",
    password: "***",
    nickname: "",
    picture: "",
    enable: 1,
    user_scope_tag: []
})

const userList = ref([{
    username: "w1134407270",
    password: "***",
    nickname: "测试",
    picture: "AAAAAAA",
    enable: 1,
    user_scope_tag: ["userinfo", "app-all"]
}])

// 用于禁用密码栏
const passwordOn = ref(false)

// 分页数量
const pageSize = ref(10)
// 分页必要数据
const totalPage = ref(1)  // 这个是后端的数据
const currentPage = ref(1)
const currentChange = (page) => { // current-page 改变时触发
    currentPage.value = page
    getUserList()
}

// 模态框
const showModel = ref(false)

const showNewInfo = () => {   // 新增
    resetInfo()
    passwordOn.value = false
    showModel.value = true
}

const showEditInfo = (rowUserInfo) => { // 修改，需要回显
    userInfo.id = rowUserInfo.id            // 它是有id的，只是没有显示
    userInfo.username = rowUserInfo.username
    userInfo.password = rowUserInfo.password
    userInfo.nickname = rowUserInfo.nickname
    userInfo.picture = rowUserInfo.picture
    userInfo.enable = rowUserInfo.enable
    userInfo.user_scope_tag = rowUserInfo.user_scope_tag
    passwordOn.value = true
    showModel.value = true
}

const resetInfo = () => {   // 需要清空
    userInfo.id = 0
    userInfo.username = ""
    userInfo.password = ""
    userInfo.nickname = ""
    userInfo.picture = ""
    userInfo.enable = 0
    userInfo.user_scope_tag = []
}

// crud
const addOrUpdateInfo = () => {
    // 判断字段是否为空
    const fieldsToSkip = ["id", "password", "picture"]; // 指定要跳过判断的字段
    const isOtherFieldsEmpty = Object.entries(userInfo).filter(([key, value]) => !fieldsToSkip.includes(key)).some(([key, value]) => {
        if (Array.isArray(value)) {
            return value.length === 0;
        } else if (typeof value === "number") {
            return false;
        } else {
            return value === "";
        }
    });
    if (isOtherFieldsEmpty) {
        ElMessage('存在未填写字段');
    } else {
        // 在这里添加
        addUserRequest()
        showModel.value = false
    }
}

const deleteInfo = (username) => {
    ElMessageBox.confirm('是否删除用户' + username, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteUserRequest(username)
    }).catch(() => {
        // 取消删除操作
        ElMessage('取消')
    });
}

// 搜索
const query = ref()
const queryUser = () => {
    if (query.value === undefined || query.value === "") {
        getUserList()
    } else {
        queryUserRequest()
    }
}
</script>
